<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="migrateChannel"
        >迁移
        </el-button>
      </el-col>
    </el-row>

    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom:20px;font-size:19px;font-weight:700;">
      <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="index">
        <span @click="To(index)" class="potor" style="font-weight:500;">{{ item.name }}</span>
      </el-breadcrumb-item>
    </el-breadcrumb>

    <el-table :show-overflow-tooltip="true" v-loading="loading" :data="dataList">
<!--      <el-table-column label="用户ID" prop="id" align="center" width="180px"/>-->
      <el-table-column label="用户ID" prop="id" align="left" width="600px">
        <template slot-scope="scope">
          <span class="potor" @click="more(scope.row)">
            {{ scope.row.id }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" prop="userName" align="center" width="140px"/>
      <el-table-column label="昵称" prop="nickName" align="center" width="140px"/>
      <el-table-column label="邀请码" prop="invitationCode" align="center" width="140px"/>
      <el-table-column label="用户类型" prop="userSysType" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.userSysType === 0">水军</el-tag>
          <el-tag type="success" v-else>正常用户</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="推广地址" prop="promotionAddress" align="center" width="400px">
        <template slot-scope="scope">
          <div>
            <el-button>{{scope.row.promotionAddress}}</el-button>
          <el-button icon="el-icon-paperclip" plain style='margin-left:0px;' @click="getUrl(scope.row)" :id="scope.row.id"></el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="推广二维码" prop="promotionCode" align="center" width="120px">
        <template slot-scope="scope">
          <div style="display: flex; justify-content: center">
            <VueQrcode :value="scope.row.promotionCode" :options="{ width: 100 }"></VueQrcode>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" fixed="right" align="center" min-width="150">
        <template slot-scope="scope">
          <div>
            <el-button size="mini" type="text" icon="el-icon-sort" @click="handleMove(scope.row)">迁移</el-button>
            <el-button size="mini" type="text" icon="el-icon-circle-plus-outline" @click="handleAddUnder(scope.row.userId)">新增下级</el-button>
          </div>
        </template>
      </el-table-column> -->
    </el-table>
    <pagination style="margin-right: 80px; margin-bottom: 50px" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList"
    />
    <!-- 添加渠道账户 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="$refs['form'].resetFields()">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入昵称"/>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入登录密码"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    迁移渠道-->
    <el-dialog title="渠道迁移" :visible.sync="open1" width="650px" append-to-body
               :close-on-click-modal="false" @close="userId=null;"
    >
      <el-form ref="formPop" :model="formMove" label-width="160px">
        <el-form-item label="选择需要迁出的用户名" prop="parentId">
           <el-select
              v-model="formMove.oldUserId"
              filterable
              remote
              clearable
              placeholder="请输入关键词"
              :remote-method="remoteMethod1"
              :loading="loading">
              <el-option
                v-for="item in dataMoveList1"
                :key="item.id"
                :label="item.nickName"
                :value="item.id">
              </el-option>
            </el-select>
          <!-- <el-select v-model="formMove.oldUserId" clearable placeholder="请选择">
            <el-option
              v-for="item in dataMoveList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id">
            </el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="选择迁移目标用户名" prop="parentId">
          <el-select
              v-model="formMove.newUserid"
              filterable
              remote
              clearable
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod2"
              :loading="loading">
              <el-option
                v-for="item in dataMoveList2"
                :key="item.id"
                :label="item.nickName"
                :value="item.id">
              </el-option>
            </el-select>
          <!-- <el-select v-model="formMove.newUserid" clearable placeholder="请选择">
            <el-option
              v-for="item in dataMoveList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id">
            </el-option>
          </el-select> -->
        </el-form-item>
        <div style="color:red;">注：渠道迁移后，迁出的用户所有伞下用户（含迁出用户）将会并入目标用户伞下</div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open1 = false">{{ $t('message.system.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm1">{{ $t('message.system.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { userChannel, addChannel,channelEdit,channelList,foundationpage } from '@/api/channel/channel'
import VueQrcode from '@chenfengyuan/vue-qrcode'
import Log from '@/views/system/job/log.vue'

export default {
  name: 'channelList',
  components: { VueQrcode },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId:null,
      },
      // 总条数
      total: 0,
      // table列表
      dataList: [],
      // 加载
      loading: false,
      // 是否显示弹出层
      open: false,
      open1: false,
      type:null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '登录密码不能为空', trigger: 'blur' }
        ]
      },
      breadcrumbList: [{ name: '一级渠道' }],
      userId:null,
      formMove:{oldUserId:null,newUserid:null},
      dataMoveList1:[],
      dataMoveList2:[],
      title:null,
      loading1:false,
      loading2:false,
    }
  },
  mounted() {
    this.getList()
    this.getAllUser(null,1)
    setTimeout(() => {
      this.getAllUser(null,2)
    }, 1000);
  },
  methods: {
     debounce (func, wait = 1000) {
        let timer = null
        return () => {
          // 前一个定时器还没结束，清空当前定时器，重新开始计时
          if (timer) {
            clearTimeout(timer)
          }
          timer = setTimeout(func, wait)
        }
      },
    remoteMethod1(query) {
        if (query !== '') {
          this.loading1 = true;
         this.debounce(this.getAllUser(query,1))  
        } else {
          this.dataMoveList1 = [];
        }
      },
      remoteMethod2(query) {
        if (query !== '') {
          this.loading2 = true;
          this.debounce(this.getAllUser(query,2))  
        } else {
          this.dataMoveList2 = [];
        }
      },
    // 迁移渠道
    migrateChannel(){
      this.formMove.oldUserId =null;
      this.formMove.newUserid = null;
      this.open1 = true
    },
    getAllUser(name,type){
      let params = {
        nickName:name,
        pageSize: 9999,
        pageNum: 1,
      }
      foundationpage(params).then(res => {
        // this.dataMoveList = res.data.records
        // console.log('this.dataMoveList',this.dataMoveList)
        if(type == 1){
          this.dataMoveList1 = res.data.records
          this.loading1 = true;
        }else{
          this.dataMoveList2 = res.data.records
          this.loading2 = true;
        }
      })
    },
    /** 查询用户列表列表 */
    getList() {
      this.loading = true
      userChannel(this.queryParams).then(response => {
        this.dataList = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // if(this.type === 1) this.form.
          addChannel(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    submitForm1(){
      let obj = {
          oldUserId: this.formMove.oldUserId,
          newUserid: this.formMove.newUserid
      }
      this.$refs["formPop"].validate(valid => {
          if (valid) {
            channelEdit(
             obj
            ).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open1 = false;
              this.getList();
            });

          }
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
      this.title = '添加渠道'
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.$refs.form.clearValidate()
    },
    getUrl(e) {
        let url = e.promotionAddress;
        let oInput = document.createElement('input');
        oInput.value = url;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象;
        console.log(oInput.value)
        document.execCommand("Copy"); // 执行浏览器复制命令
        this.$message({
          message: '复制成功',
          type: 'success'
        });
        oInput.remove()
    },
    // 添加下级渠道
    handleAddUnder(){
      this.form = {
        userName:null,
        nickName:null,
        password:null,
      }
      this.open = true;
      this.type = 1;
      this.title = '添加下级渠道'
    },
    handleMove(row) {
      
      console.log(row);
      this.userId = row.id
      this.open1 = true;
      
      channelList().then(res => {
        console.log(res.data);
        this.dataMoveList = res.data
        console.log('this.dataMoveList',this.dataMoveList)
      })
    },
    To(index) {
      if (index + 1 == this.breadcrumbList.length) return
      console.log('this.breadcrumbList',this.breadcrumbList,index)
      this.queryParams.userId = this.breadcrumbList[index].id
      this.queryParams.page = 1
      if (index) {
        this.more()
      } else {
        this.queryParams.userId = null
        this.more()
      }
      let arr = this.breadcrumbList
      let arr1 = []
      arr.splice(index + 1, 1000)
      arr.forEach((item, index) => {
        arr1.push(item)
      })
      this.breadcrumbList = arr1
    },

    more(row) {
      if (row) {
        this.queryParams.page = 1
        this.queryParams.userId = row.id
      }
      this.loading = true
      userChannel(this.queryParams).then((res) => {
        if (res.data.total) {
          this.dataList = res.data.records
          this.total = res.data.total
          this.loading = false
          if (row) {
            this.breadcrumbList.push({ name: row.nickName, id: row.id })
          }
        } else {
          this.loading = false
          this.$message.error('WARRING')
        }
      }).catch(err => {
        this.loading = false
      })
    },
  }
}
</script>
<style scoped lang="scss">
.potor {
  cursor: pointer;
}

</style>
